@{
    ViewData["Title"] = "编辑BOM";
}

@section Styles {
    <link rel="stylesheet" href="~/layui/css/layui.css" />
}

@section Scripts {
    <script src="~/layui/layui.js"></script>
}

<div class="layui-container">
    <div class="layui-row">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h3>编辑BOM</h3>
                </div>
                <div class="layui-card-body">
                    <form class="layui-form" id="bomEditForm">
                        <input type="hidden" id="bomId" name="Id" />
                        
                        <!-- 基本信息 -->
                        <fieldset class="layui-elem-field">
                            <legend>基本信息</legend>
                            <div class="layui-field-box">
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">BOM编号</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="BOMCode" id="bomCode" lay-verify="required" placeholder="请输入BOM编号" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">BOM名称</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="BOMTitle" id="bomTitle" lay-verify="required" placeholder="请输入BOM名称" class="layui-input">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">产品编号</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="ProductsCode" id="productsCode" placeholder="请输入产品编号" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">产品名称</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="ProductsName" id="productsName" placeholder="请输入产品名称" class="layui-input">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">规格型号</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="ProductsModel" id="productsModel" placeholder="请输入规格型号" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">单位</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="ProductsUnit" id="productsUnit" placeholder="请输入单位" class="layui-input">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">品牌</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="Brand" id="brand" placeholder="请输入品牌" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">版本号</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="Version" id="version" placeholder="请输入版本号" class="layui-input">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">日产量</label>
                                        <div class="layui-input-inline">
                                            <input type="number" name="Output" id="output" placeholder="请输入日产量" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">状态</label>
                                        <div class="layui-input-inline">
                                            <input type="checkbox" name="Status" id="status" lay-skin="switch" lay-text="启用|禁用">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">备注</label>
                                        <div class="layui-input-block">
                                            <textarea name="Desc" id="desc" placeholder="请输入备注" class="layui-textarea"></textarea>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </fieldset>

                        <!-- 配件管理 -->
                        <fieldset class="layui-elem-field">
                            <legend>配件管理</legend>
                            <div class="layui-field-box">
                                                                 <div class="layui-form-item">
                                     <div class="layui-input-block">
                                         <button type="button" class="layui-btn layui-btn-sm" onclick="addGoodsRow()">
                                             <i class="layui-icon">&#xe654;</i> 添加配件
                                         </button>
                                     </div>
                                 </div>
                                <div class="layui-form-item">
                                    <div class="layui-input-block">
                                        <table class="layui-table" id="goodsTable">
                                            <thead>
                                                <tr>
                                                    <th>序号</th>
                                                    <th>物品编号</th>
                                                    <th>物品名称</th>
                                                    <th>规格型号</th>
                                                    <th>单位</th>
                                                    <th>操作</th>
                                                </tr>
                                            </thead>
                                            <tbody id="goodsTableBody">
                                                <!-- 配件行将通过JavaScript动态添加 -->
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </fieldset>

                        <!-- 工艺流程管理 -->
                        <fieldset class="layui-elem-field">
                            <legend>工艺流程管理</legend>
                            <div class="layui-field-box">
                                <div class="layui-form-item">
                                    <div class="layui-input-block">
                                        <button type="button" class="layui-btn layui-btn-sm" onclick="addFlowRow()">
                                            <i class="layui-icon">&#xe654;</i> 添加工序
                                        </button>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <div class="layui-input-block">
                                        <table class="layui-table" id="flowTable">
                                            <thead>
                                                <tr>
                                                    <th>序号</th>
                                                    <th>工序编号</th>
                                                    <th>工序名称</th>
                                                    <th>工序数量</th>
                                                    <th>负责人</th>
                                                    <th>所属部门</th>
                                                    <th>操作</th>
                                                </tr>
                                            </thead>
                                            <tbody id="flowTableBody">
                                                <!-- 工序行将通过JavaScript动态添加 -->
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </fieldset>

                        <!-- 操作按钮 -->
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button class="layui-btn" lay-submit lay-filter="submitForm">保存修改</button>
                                <button type="button" class="layui-btn layui-btn-primary" onclick="goBack()">返回</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    var bomId = 0;
    var bomDetail = null;
    var goodsList = [];
    var flowList = [];

    $(document).ready(function() {
        // 等待Layui加载完成
        layui.use(['form', 'layer'], function(){
            var form = layui.form;
            var layer = layui.layer;
            
            // 获取BOM ID
            bomId = getBomIdFromUrl();
            if (!bomId) {
                layer.msg('未能获取到BOM ID', {icon: 2});
                return;
            }

            // 加载BOM详情
            loadBomDetail();
            
            // 监听提交
            form.on('submit(submitForm)', function(data){
                submitForm();
                return false;
            });
        });
    });

    // 获取BOM ID
    function getBomIdFromUrl() {
        // 优先从localStorage获取
        var id = localStorage['bomId'];
        if (id) {
            var parsedId = parseInt(id);
            return parsedId;
        }
        
        // 从URL查询参数获取
        var urlParams = new URLSearchParams(window.location.search);
        id = urlParams.get('id');
        if (id) {
            var parsedId = parseInt(id);
            return parsedId;
        }
        
        // 从ViewBag获取
        var viewBagId = '@ViewBag.BomId';
        if (viewBagId && viewBagId !== '') {
            var parsedId = parseInt(viewBagId);
            return parsedId;
        }
        
        return 0;
    }

    // 加载BOM详情
    function loadBomDetail() {
        if (!bomId || bomId <= 0) {
            layer.msg('BOM ID无效: ' + bomId, {icon: 2});
            return;
        }
        
        var loadIndex = layer.load(1, {shade: [0.3, '#000']});
        
        $.ajax({
            url: 'http://localhost:5141/api/Bom/GetBomDetail',
            type: 'GET',
            data: { id: bomId },
            success: function(res) {
                layer.close(loadIndex);
                
                if (res && res.code === 200 && res.data) {
                    bomDetail = res.data;
                    
                    // 渲染表单数据
                    renderFormData();
                } else {
                    layer.msg('获取BOM详情失败: ' + (res.message || '未知错误'), {icon: 2});
                }
            },
            error: function(xhr, status, error) {
                layer.close(loadIndex);
                console.error('请求BOM详情失败:', {xhr, status, error});
                layer.msg('请求失败: ' + error, {icon: 2});
            }
        });
    }

    // 渲染表单数据
    function renderFormData() {
        if (!bomDetail) return;
        
        // 获取BOM基本信息
        var bom = bomDetail.bomInfo || bomDetail.BomInfo || bomDetail;
        if (!bom) return;
        
        // 填充基本信息
        $('#bomId').val(bomId);
        $('#bomCode').val(bom.bomCode || bom.BOMCode || '');
        $('#bomTitle').val(bom.bomTitle || bom.BOMTitle || '');
        $('#productsCode').val(bom.productsCode || bom.ProductsCode || '');
        $('#productsName').val(bom.productsName || bom.ProductsName || '');
        $('#productsModel').val(bom.productsModel || bom.ProductsModel || '');
        $('#productsUnit').val(bom.productsUnit || bom.ProductsUnit || '');
        $('#brand').val(bom.brand || bom.Brand || '');
        $('#version').val(bom.version || bom.Version || '');
        $('#output').val(bom.output || bom.Output || 0);
        $('#desc').val(bom.desc || bom.Desc || '');
        
        // 设置状态
        var status = bom.status || bom.Status || false;
        $('#status').prop('checked', status);
        
        // 重新渲染表单
        layui.form.render();
        
        // 渲染配件列表
        renderGoodsList();
        
        // 渲染工艺流程列表
        renderFlowList();
    }

    // 渲染配件列表
    function renderGoodsList() {
        var components = bomDetail.goodsList || bomDetail.GoodsList || bomDetail.bomRelations || [];
        goodsList = [];
        
        if (Array.isArray(components) && components.length > 0) {
            components.forEach(function(item, index) {
                var goodsInfo = item.goodsinfo || item.Goodsinfo || item;
                if (goodsInfo) {
                    goodsList.push({
                        id: goodsInfo.id || goodsInfo.Id || 0,
                        goodsCode: goodsInfo.goodsCode || goodsInfo.GoodsCode || '',
                        goodsName: goodsInfo.goodsName || goodsInfo.GoodsName || '',
                        goodsModel: goodsInfo.goodsModel || goodsInfo.GoodsModel || '',
                        unit: goodsInfo.unit || goodsInfo.Unit || ''
                    });
                }
            });
        }
        
        refreshGoodsTable();
    }

    // 渲染工艺流程列表
    function renderFlowList() {
        var flows = bomDetail.flowList || bomDetail.FlowList || bomDetail.bomFlowRelation || [];
        flowList = [];
        
        if (Array.isArray(flows) && flows.length > 0) {
            flows.forEach(function(item, index) {
                var flowInfo = item.processFlow || item.ProcessFlow || item;
                if (flowInfo) {
                    flowList.push({
                        id: flowInfo.id || flowInfo.Id || 0,
                        flowCode: flowInfo.flowCode || flowInfo.FlowCode || '',
                        flowName: flowInfo.flowName || flowInfo.FlowName || '',
                        flowNumber: flowInfo.flowNumber || flowInfo.FlowNumber || '',
                        responsible: flowInfo.responsible || flowInfo.Responsible || '',
                        department: flowInfo.department || flowInfo.Department || ''
                    });
                }
            });
        }
        
        refreshFlowTable();
    }

    // 刷新配件表格
    function refreshGoodsTable() {
        var str = '';
        if (goodsList.length > 0) {
            goodsList.forEach(function(item, index) {
                str += `<tr data-id="${item.id || ''}">
                    <td>${index + 1}</td>
                    <td>${item.goodsCode || ''}</td>
                    <td>${item.goodsName || ''}</td>
                    <td>${item.goodsModel || ''}</td>
                    <td>${item.unit || ''}</td>
                    <td>
                        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" onclick="removeGoodsRow(${index})">
                            <i class="layui-icon">&#xe640;</i> 删除
                        </button>
                    </td>
                </tr>`;
            });
        } else {
            str = '<tr><td colspan="6" style="text-align:center;color:#999;">暂无配件</td></tr>';
        }
        $('#goodsTableBody').html(str);
    }

    // 刷新工艺流程表格
    function refreshFlowTable() {
        var str = '';
        if (flowList.length > 0) {
            flowList.forEach(function(item, index) {
                str += `<tr data-id="${item.id || ''}">
                    <td>${index + 1}</td>
                    <td>${item.flowCode || ''}</td>
                    <td>${item.flowName || ''}</td>
                    <td>${item.flowNumber || ''}</td>
                    <td>${item.responsible || ''}</td>
                    <td>${item.department || ''}</td>
                    <td>
                        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" onclick="removeFlowRow(${index})">
                            <i class="layui-icon">&#xe640;</i> 删除
                        </button>
                    </td>
                </tr>`;
            });
        } else {
            str = '<tr><td colspan="7" style="text-align:center;color:#999;">暂无工序</td></tr>';
        }
        $('#flowTableBody').html(str);
    }

    // 添加配件行
    function addGoodsRow() {
        // 加载物品列表
        loadGoodsListForSelection();
    }

    // 加载物品列表供选择
    function loadGoodsListForSelection() {
        var loadIndex = layer.load(1, {shade: [0.3, '#000']});
        
        $.ajax({
            url: 'http://localhost:5141/api/Goods/GetGoodsinfo',
            type: 'GET',
            data: { 
                pageIndex: 1, 
                pageSize: 100,
                goodsCode: '',
                goodsName: '',
                goodsType: '',
                status: 1
            },
            success: function(res) {
                layer.close(loadIndex);
                
                if (res && res.code === 200 && res.pageData) {
                    var goodsData = res.pageData;
                    showGoodsSelectionModal(goodsData);
                } else {
                    layer.msg('获取物品列表失败: ' + (res.message || '未知错误'), {icon: 2});
                }
            },
            error: function(xhr, status, error) {
                layer.close(loadIndex);
                console.error('获取物品列表失败:', {xhr, status, error});
                layer.msg('请求失败: ' + error, {icon: 2});
            }
        });
    }

    // 显示物品选择弹窗
    function showGoodsSelectionModal(goodsData) {
        var content = `
            <div style="padding: 20px;">
                <div class="layui-form-item">
                    <div class="layui-input-inline" style="width: 200px;">
                        <input type="text" id="goodsSearch" placeholder="搜索物品编号或名称" class="layui-input">
                    </div>
                    <div class="layui-input-inline" style="width: 100px;">
                        <button type="button" class="layui-btn layui-btn-sm" onclick="searchGoods()">搜索</button>
                    </div>
                </div>
                <div class="layui-form-item">
                    <table class="layui-table" id="goodsSelectionTable">
                        <thead>
                            <tr>
                                <th><input type="checkbox" lay-skin="primary" id="selectAllGoods"></th>
                                <th>物品编号</th>
                                <th>物品名称</th>
                                <th>规格型号</th>
                                <th>单位</th>
                                <th>类型</th>
                            </tr>
                        </thead>
                        <tbody id="goodsSelectionTableBody">
                            ${renderGoodsSelectionRows(goodsData)}
                        </tbody>
                    </table>
                </div>
            </div>
        `;

        layui.use(['layer'], function(){
            var layer = layui.layer;
            var layerIndex = layer.open({
                type: 1,
                title: '选择配件',
                area: ['900px', '600px'],
                content: content,
                btn: ['确定', '取消'],
                yes: function(index, layero) {
                    // 获取选中的物品
                    var selectedGoods = getSelectedGoods();
                    
                    if (selectedGoods.length > 0) {
                        // 添加到当前配件列表
                        selectedGoods.forEach(function(goods) {
                            // 检查是否已经存在 - 修复ID比较逻辑
                            var exists = false;
                            if (goodsList.length > 0) {
                                exists = goodsList.some(function(item) {
                                    // 确保ID类型一致进行比较
                                    return parseInt(item.id) === parseInt(goods.id);
                                });
                            }
                            
                            if (!exists) {
                                var newGoods = {
                                    id: parseInt(goods.id) || 0,
                                    goodsCode: goods.goodsCode || goods.GoodsCode || '',
                                    goodsName: goods.goodsName || goods.GoodsName || '',
                                    goodsModel: goods.goodsModel || goods.GoodsModel || '',
                                    unit: goods.unit || goods.Unit || ''
                                };
                                goodsList.push(newGoods);
                            }
                        });
                        
                        refreshGoodsTable();
                    }
                    layer.close(index);
                },
                btn2: function(index, layero) {
                    layer.close(index);
                },
                success: function(layero, index) {
                    layui.use('form', function() {
                        var form = layui.form;
                        form.render('checkbox'); // 渲染弹窗内的checkbox
                        // 重新绑定搜索按钮和全选checkbox的事件
                        $('#goodsSearchBtn').off('click').on('click', searchGoods);
                        $('#goodsSelectionTable thead input[type="checkbox"]').off('change').on('change', function() {
                            var checked = this.checked;
                            $('#goodsSelectionTableBody input[type="checkbox"]').prop('checked', checked);
                            form.render('checkbox'); // 重新渲染checkbox状态
                        });
                    });
                }
            });
        });

        // 绑定全选事件
        $('#selectAllGoods').on('change', function() {
            var checked = $(this).prop('checked');
            $('#goodsSelectionTableBody input[type="checkbox"]').prop('checked', checked);
        });
    }

    // 渲染物品选择行
    function renderGoodsSelectionRows(goodsList) {
        var str = '';
        if (goodsList && goodsList.length > 0) {
            goodsList.forEach(function(item, index) {
                str += `<tr>
                    <td><input type="checkbox" lay-skin="primary" value="${item.id}" data-goods='${JSON.stringify(item).replace(/'/g, "&apos;")}'></td>
                    <td>${item.goodsCode || item.GoodsCode || ''}</td>
                    <td>${item.goodsName || item.GoodsName || ''}</td>
                    <td>${item.goodsModel || item.GoodsModel || ''}</td>
                    <td>${item.unit || item.Unit || ''}</td>
                    <td>${item.goodsType || item.GoodsType || ''}</td>
                </tr>`;
            });
        } else {
            str = '<tr><td colspan="6" style="text-align:center;color:#999;">暂无数据</td></tr>';
        }
        return str;
    }

    // 获取选中的物品
    function getSelectedGoods() {
        var selectedGoods = [];
        var checkedBoxes = $('#goodsSelectionTableBody input[type="checkbox"]:checked');
        
        checkedBoxes.each(function() {
            var goodsData = $(this).data('goods');
            if (goodsData) {
                selectedGoods.push(goodsData);
            }
        });
        return selectedGoods;
    }

    // 搜索物品
    function searchGoods() {
        var searchText = $('#goodsSearch').val().trim();
        if (!searchText) {
            loadGoodsListForSelection();
            return;
        }

        var loadIndex = layer.load(1, {shade: [0.3, '#000']});
        
        $.ajax({
            url: 'http://localhost:5141/api/Goods/GetGoodsinfo',
            type: 'GET',
            data: { 
                pageIndex: 1, 
                pageSize: 100,
                goodsCode: searchText,
                goodsName: searchText,
                goodsType: '',
                status: 1
            },
            success: function(res) {
                layer.close(loadIndex);
                if (res && res.code === 200 && res.pageData) {
                    var goodsData = res.pageData;
                    $('#goodsSelectionTableBody').html(renderGoodsSelectionRows(goodsData));
                } else {
                    $('#goodsSelectionTableBody').html('<tr><td colspan="6" style="text-align:center;color:#999;">搜索无结果</td></tr>');
                }
            },
            error: function(xhr, status, error) {
                layer.close(loadIndex);
                console.error('搜索物品失败:', {xhr, status, error});
                layer.msg('搜索失败: ' + error, {icon: 2});
            }
        });
    }

    // 添加工序行
    function addFlowRow() {
        // 加载工艺流程列表
        loadProcessFlowListForSelection();
    }

    // 加载工艺流程列表供选择
    function loadProcessFlowListForSelection() {
        var loadIndex = layer.load(1, {shade: [0.3, '#000']});
        
        $.ajax({
            url: 'http://localhost:5141/api/ProcessFlow/GetProcessFlow',
            type: 'GET',
            data: { 
                pageIndex: 1, 
                pageSize: 100,
                flowCode: '',
                flowName: '',
                status: 1
            },
            success: function(res) {
                layer.close(loadIndex);
                
                if (res && res.code === 200 && res.pageData) {
                    var flowData = res.pageData;
                    showProcessFlowSelectionModal(flowData);
                } else {
                    layer.msg('获取工艺流程列表失败: ' + (res.message || '未知错误'), {icon: 2});
                }
            },
            error: function(xhr, status, error) {
                layer.close(loadIndex);
                console.error('获取工艺流程列表失败:', {xhr, status, error});
                layer.msg('请求失败: ' + error, {icon: 2});
            }
        });
    }

    // 显示工艺流程选择弹窗
    function showProcessFlowSelectionModal(flowData) {
        var content = `
            <div style="padding: 20px;">
                <div class="layui-form-item">
                    <div class="layui-input-inline" style="width: 200px;">
                        <input type="text" id="flowSearch" placeholder="搜索工序编号或名称" class="layui-input">
                    </div>
                    <div class="layui-input-inline" style="width: 100px;">
                        <button type="button" class="layui-btn layui-btn-sm" onclick="searchProcessFlow()">搜索</button>
                    </div>
                </div>
                <div class="layui-form-item">
                    <table class="layui-table" id="flowSelectionTable">
                        <thead>
                            <tr>
                                <th><input type="checkbox" lay-skin="primary" id="selectAllFlow"></th>
                                <th>工序编号</th>
                                <th>工序名称</th>
                                <th>工序数量</th>
                                <th>负责人</th>
                                <th>所属部门</th>
                            </tr>
                        </thead>
                        <tbody id="flowSelectionTableBody">
                            ${renderProcessFlowSelectionRows(flowData)}
                        </tbody>
                    </table>
                </div>
            </div>
        `;

        layui.use(['layer'], function(){
            var layer = layui.layer;
            var layerIndex = layer.open({
                type: 1,
                title: '选择工序',
                area: ['900px', '600px'],
                content: content,
                btn: ['确定', '取消'],
                yes: function(index, layero) {
                    // 获取选中的工序
                    var selectedFlows = getSelectedProcessFlows();
                    
                    if (selectedFlows.length > 0) {
                        // 添加到当前工序列表
                        selectedFlows.forEach(function(flow) {
                            // 检查是否已经存在
                            var exists = flowList.some(function(item) {
                                return item.id === flow.id;
                            });
                            if (!exists) {
                                var newFlow = {
                                    id: flow.id,
                                    flowCode: flow.flowCode || flow.FlowCode,
                                    flowName: flow.flowName || flow.FlowName,
                                    flowNumber: flow.flowNumber || flow.FlowNumber,
                                    responsible: flow.responsible || flow.Responsible,
                                    department: flow.department || flow.Department
                                };
                                flowList.push(newFlow);
                            }
                        });
                        refreshFlowTable();
                    }
                    layer.close(index);
                },
                btn2: function(index, layero) {
                    layer.close(index);
                },
                success: function(layero, index) {
                    layui.use('form', function() {
                        var form = layui.form;
                        form.render('checkbox'); // 渲染弹窗内的checkbox
                        // 重新绑定搜索按钮和全选checkbox的事件
                        $('#flowSearchBtn').off('click').on('click', searchProcessFlow);
                        $('#flowSelectionTable thead input[type="checkbox"]').off('change').on('change', function() {
                            var checked = this.checked;
                            $('#flowSelectionTableBody input[type="checkbox"]').prop('checked', checked);
                            form.render('checkbox'); // 重新渲染checkbox状态
                        });
                    });
                }
            });
        });

        // 绑定全选事件
        $('#selectAllFlow').on('change', function() {
            var checked = $(this).prop('checked');
            $('#flowSelectionTableBody input[type="checkbox"]').prop('checked', checked);
        });
    }

    // 渲染工艺流程选择行
    function renderProcessFlowSelectionRows(flowList) {
        var str = '';
        if (flowList && flowList.length > 0) {
            flowList.forEach(function(item, index) {
                str += `<tr>
                    <td><input type="checkbox" lay-skin="primary" value="${item.id}" data-flow='${JSON.stringify(item).replace(/'/g, "&apos;")}'></td>
                    <td>${item.flowCode || item.FlowCode || ''}</td>
                    <td>${item.flowName || item.FlowName || ''}</td>
                    <td>${item.flowNumber || item.FlowNumber || ''}</td>
                    <td>${item.responsible || item.Responsible || ''}</td>
                    <td>${item.department || item.Department || ''}</td>
                </tr>`;
            });
        } else {
            str = '<tr><td colspan="6" style="text-align:center;color:#999;">暂无数据</td></tr>';
        }
        return str;
    }

    // 获取选中的工序
    function getSelectedProcessFlows() {
        var selectedFlows = [];
        var checkedBoxes = $('#flowSelectionTableBody input[type="checkbox"]:checked');
        
        checkedBoxes.each(function() {
            var flowData = $(this).data('flow');
            if (flowData) {
                selectedFlows.push(flowData);
            }
        });
        return selectedFlows;
    }

    // 搜索工艺流程
    function searchProcessFlow() {
        var searchText = $('#flowSearch').val().trim();
        if (!searchText) {
            loadProcessFlowListForSelection();
            return;
        }

        var loadIndex = layer.load(1, {shade: [0.3, '#000']});
        
        $.ajax({
            url: 'http://localhost:5141/api/ProcessFlow/GetProcessFlow',
            type: 'GET',
            data: { 
                pageIndex: 1, 
                pageSize: 100,
                flowCode: searchText,
                flowName: searchText,
                status: 1
            },
            success: function(res) {
                layer.close(loadIndex);
                if (res && res.code === 200 && res.pageData) {
                    var flowData = res.pageData;
                    $('#flowSelectionTableBody').html(renderProcessFlowSelectionRows(flowData));
                } else {
                    $('#flowSelectionTableBody').html('<tr><td colspan="6" style="text-align:center;color:#999;">搜索无结果</td></tr>');
                }
            },
            error: function(xhr, status, error) {
                layer.close(loadIndex);
                console.error('搜索工艺流程失败:', {xhr, status, error});
                layer.msg('搜索失败: ' + error, {icon: 2});
            }
        });
    }

    // 删除配件行
    function removeGoodsRow(index) {
        layer.confirm('确认删除该配件吗？', {icon: 3, title: '提示'}, function(index) {
            goodsList.splice(index, 1);
            refreshGoodsTable();
            layer.close(index);
        });
    }

    // 删除工序行
    function removeFlowRow(index) {
        layer.confirm('确认删除该工序吗？', {icon: 3, title: '提示'}, function(index) {
            flowList.splice(index, 1);
            refreshFlowTable();
            layer.close(index);
        });
    }

    // 提交表单
    function submitForm() {
        // 防止重复提交
        if (window.isSubmitting) {
            return false;
        }
        
        // 验证表单
        if (!validateForm()) {
            return false;
        }

        // 构建提交数据
        // 构建关系数组
        var finalGoodsRelations = [];
        var finalFlowRelations = [];
        
        // 从当前前端状态构建关系
        if (goodsList && goodsList.length > 0) {
            goodsList.forEach(function(item) {
                var id = parseInt(item.id || item.goodsinfoId || 0);
                if (id > 0) {
                    finalGoodsRelations.push({ GoodsinfoId: id });
                }
            });
        }
        
        if (flowList && flowList.length > 0) {
            flowList.forEach(function(item) {
                var id = parseInt(item.id || item.processFlowId || 0);
                if (id > 0) {
                    finalFlowRelations.push({ ProcessFlowId: id });
                }
            });
        }

        // 判断是否保留原有关系（当前端没有选择关系时）
        var keepExistingRelations = (finalGoodsRelations.length === 0 && finalFlowRelations.length === 0);

        var formData = {
            Id: bomId,
            BOMCode: $('#bomCode').val(),
            BOMTitle: $('#bomTitle').val(),
            ProductsCode: $('#productsCode').val(),
            ProductsName: $('#productsName').val(),
            ProductsModel: $('#productsModel').val(),
            ProductsUnit: $('#productsUnit').val(),
            Brand: $('#brand').val(),
            Version: $('#version').val(),
            Output: parseInt($('#output').val()) || 0,
            Status: $('#status').is(':checked'),
            Desc: $('#desc').val().trim(),
            GoodsRelations: finalGoodsRelations,
            FlowRelations: finalFlowRelations,
            KeepExistingRelations: keepExistingRelations
        };

        console.log('提交数据:', formData);
        console.log('BOM ID:', bomId);
        console.log('是否保留原有关系:', formData.KeepExistingRelations);
        console.log('配件关系:', finalGoodsRelations);
        console.log('工序关系:', finalFlowRelations);

        // 设置提交状态
        window.isSubmitting = true;
        
        // 显示加载
        var loadIndex = layer.load(1, {shade: [0.3, '#000']});

        // 发送请求
        $.ajax({
            url: 'http://localhost:5141/api/Bom/UpdateBom',
            type: 'POST',
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function(res) {
                layer.close(loadIndex);
                window.isSubmitting = false;
                
                if (res && res.code === 200 && res.data > 0) {
                    layer.msg('BOM更新成功！', {
                        icon: 1,
                        time: 1500
                    });
                    // 轻提示后刷新数据
                    setTimeout(function(){ loadBomDetail(); }, 1600);
                } else {
                    layer.msg('更新失败: ' + (res.message || '未知错误'), {icon: 2});
                }
            },
            error: function(xhr, status, error) {
                layer.close(loadIndex);
                window.isSubmitting = false;
                
                console.error('更新BOM失败:', {xhr, status, error});
                layer.msg('请求失败: ' + error, {icon: 2});
            }
        });
        
        return false;
    }

    // 验证表单
    function validateForm() {
        var bomCode = $('#bomCode').val().trim();
        var bomTitle = $('#bomTitle').val().trim();
        
        if (!bomCode) {
            layer.msg('请输入BOM编号', {icon: 2});
            $('#bomCode').focus();
            return false;
        }
        
        if (!bomTitle) {
            layer.msg('请输入BOM名称', {icon: 2});
            $('#bomTitle').focus();
            return false;
        }
        
        return true;
    }

    // 返回
    function goBack() {
        if (window.parent && window.parent.loadPage) {
            window.parent.loadPage('/Bom/BomList', 'BOM列表');
        } else {
            location.href = '/Bom/BomList';
        }
    }


</script>
